package com.foreveross.bsl.mam.app.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreveross.bsl.auth.AuthAccount;
import com.foreveross.bsl.auth.constant.Constant;
import com.foreveross.bsl.auth.service.IdentityService;
import com.foreveross.bsl.mam.app.application.AppCategoryApplication;
import com.foreveross.bsl.mam.app.application.AppMainApplication;
import com.foreveross.bsl.mam.app.application.AppVersionApplication;
import com.foreveross.bsl.mam.app.application.AppVersionWidgetVersionApplication;
import com.foreveross.bsl.mam.app.application.vo.AppCategoryVo;
import com.foreveross.bsl.mam.app.application.vo.AppMainVo;
import com.foreveross.bsl.mam.app.application.vo.AppVersionVo;
import com.foreveross.bsl.system.application.AppCloudLinkService;
import com.foreveross.bsl.system.application.ApplicationRegisterApplication;
import com.foreveross.bsl.system.application.CloudFunctionService;
import com.foreveross.bsl.system.application.vo.CloudFunctionVo;

/**
 * 应用类别操作类
 * 
 * @author tanzhixiong
 * @2013-6-22 @下午3:01:42
 */
@Controller
@RequestMapping("/mam/appMain")
public class AppMainCountroller extends AppBaseController {

	@Inject
	private AppMainApplication appMainApplication;

	@Inject
	private AppCategoryApplication appCategoryApplication;

	@Inject
	private AppVersionApplication appVersionApplication;

	@Inject
	private AppCloudLinkService appCloudLinkService;

	@Inject
	private CloudFunctionService cloudFunctionApplication;

	@Inject
	private AppCloudLinkService appCloudLinkApplication;

	@Inject
	private ApplicationRegisterApplication applicationRegisterApplication;

	@Inject
	private IdentityService identityService;

	@Inject
	private AppVersionWidgetVersionApplication appVersionWidgetVersionApplication;
	
	
	/**
	 * 首页数据接口
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/list-view")
	public String showAppInfo(Model model) {
		// 获取所有 应用类别 对应的应用
		List<AppCategoryVo> appCategoryVolist = this.appCategoryApplication.findAll();
		List<AppCategoryVo> list = new ArrayList<AppCategoryVo>();
		for (int i = 0; i < appCategoryVolist.size(); i++) {
			// 应用类别
			AppCategoryVo category = appCategoryVolist.get(i);
			List<AppMainVo> appMainVolist = this.appMainApplication.getEntitybyCategoryId(category.getId());
			if (appMainVolist != null && appMainVolist.size() > 0) {
				for (AppMainVo app : appMainVolist) {
					List<AppVersionVo> appVersionList = appVersionApplication
							.getAppStatus(app.getId(), 4); // 获取发布版本
					if (appVersionList != null && appVersionList.size() > 0) {
						app.setAppVersionlist(appVersionList);
					}
					// 获取云服务
					String userId = this.getCurrentUserId();
					List<CloudFunctionVo> cloudList = appCloudLinkService
							.getLinkedCloudFunctions(userId, app.getId());
					if (cloudList != null && cloudList.size() > 0) {
						app.setCloudList(cloudList);
					}
					String appKey = this.applicationRegisterApplication.getAppKeyByAppId(app.getId());
					app.setAppKey(appKey);
				}
				category.setAppMainlist(appMainVolist);
				list.add(category);
			}
		}
		model.addAttribute("list", list);
		return "app/appInfo-list";
	}
	
	/**
	 * 此方法描述的是：查询关联应用
	 * 
	 * @author: heyaowen
	 * @version: 20141030
	 */
	@RequestMapping(value = "/{appId}/appRelations", method = RequestMethod.GET)
	public String contactAppMains(@PathVariable("appId") String appId, Model model) {
		// 获取应用(包含已关联)
		AppMainVo appVo = this.appMainApplication.findApp(appId);
		if(appVo.getAppMains() == null) // 未关联设备
			appVo.setAppMains(new ArrayList<AppMainVo>());
		// 获取未关联应用
		List<AppMainVo> unLinkApp = this.appMainApplication.findAll();
		unLinkApp.remove(appVo); // 删除自己
		unLinkApp.removeAll(appVo.getAppMains());
		model.addAttribute("appId", appId);
		model.addAttribute("linkAppMain", appVo.getAppMains());
		model.addAttribute("noLinkAppMain", unLinkApp);
		return "app/showApp";
	}
	
	/** 注意加上@ResponseBody后 此方法为直接返回json字符串，没有mvc
	 * 此方法描述的是：关联应用
	 * 
	 * @author: heyaowen
	 * @version: 20141030
	 */
	@ResponseBody
	@RequestMapping(value = "/{appId}/appLinks", method = RequestMethod.PUT)
	public Map<String, String> linkAppMains(@PathVariable("appId") String appId, @RequestBody List<String> relationships) {
		Map<String, String> result = new HashMap<String, String>();
		this.appMainApplication.addApps(appId, relationships);
		result.put("result", "success");
		return result;
	}
	
	/** 注意加上@ResponseBody后 此方法为直接返回json字符串，没有mvc
	 * 此方法描述的是：取消关联应用
	 * 
	 * @author: heyaowen
	 * @version: 20141030
	 */
	@ResponseBody
	@RequestMapping(value = "/{appId}/appUnlinks", method = RequestMethod.PUT)
	public Map<String, String> unLinkAppMains(@PathVariable("appId") String appId, @RequestBody List<String> relationships) {
		Map<String, String> result = new HashMap<String, String>();		
		this.appMainApplication.delApps(appId, relationships);
		result.put("result", "success");
		return result;
	}
	
	/**
	 * 此方法描述的是：检查应用标识是否存在
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 下午4:55:28
	 */
	@ResponseBody
	@RequestMapping("/checkIdentify")
	public Map<String, String> checkIdentify(@RequestParam String identify) {

		Map<String, String> result = new HashMap<String, String>();
		AppMainVo res = appMainApplication.getEntitybyIdentify(identify);
		if (res != null) {
			result.put("result", "true");
		} else {
			result.put("result", "false");
		}
		return result;
	}

	/**
	 * 此方法描述的是：检查应用名称是否存在
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 下午4:55:28
	 */
	@ResponseBody
	@RequestMapping("/checkName")
	public Map<String, String> checkName(@RequestParam("checkName") String name) {

		Map<String, String> result = new HashMap<String, String>();
		AppMainVo res = appMainApplication.checkName(name);
		if (res != null) {
			result.put("result", "true");
		} else {
			result.put("result", "false");
		}
		return result;
	}

	/**
	 * 进入创建应用页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/add-view")
	public String createApp(Model model) {
		List<AppCategoryVo> list = appCategoryApplication.findAll();
		model.addAttribute("lists", list);
		return "app/add-view";
	}

	@RequestMapping("/add")
	public String add(HttpServletRequest request, AppMainVo appMainVo) {
		Date date = new Date();
		String secret = UUID.randomUUID().toString();
		appMainVo.setCreate_time(date);
		appMainVo.setModified_time(date);
		appMainVo.setAvailable(1);
		appMainVo.setSecret(secret);
		AppMainVo app = appMainApplication.saveEntity(appMainVo);

		// 创建应用时候，生成一个appkey
		String sessionKey = (String) request.getSession().getAttribute(Constant.SESSION_KEY);
		Object o = identityService.validateTicket(sessionKey);
		if (o instanceof AuthAccount) {
			AuthAccount vo = (AuthAccount) o;
			applicationRegisterApplication.generateAppKey(vo.getAccountId(), vo.getAccountUsername(), app.getId(), 
					app.getApp_name(), app.getDiscription(), null);
		}

		// 生成默认两个平台
		Map<String, String> mapPlat = new HashMap<String, String>();
		String version = "1.0.0";// 默认版本
		mapPlat.put("ios", version);
		mapPlat.put("android", version);
		for (String key : mapPlat.keySet()) {
			AppVersionVo appVersion = new AppVersionVo();
			appVersion.setBuild(1);
			appVersion.setBundle("");
			appVersion.setRelease_note(app.getDiscription());
			appVersion.setApplicationid(app.getId());
			appVersion.setPlatformid(key);
			appVersion.setVersion(mapPlat.get(key));
			appVersion.setCreate_time(date);
			appVersion.setModified_time(date);
			appVersion.setAvailable("1");
			appVersion.setStatus(1);
			appVersionApplication.saveEntity(appVersion);
		}
		return "redirect:app-view/" + app.getId();
	}

	/**
	 * 
	 * 应用详细页
	 * 
	 * @param request
	 * @param appMainid
	 * @return
	 */
	@RequestMapping("/app-view/{appid}")
	public String view(@PathVariable("appid") String appid, Model model,
			HttpServletRequest request) {
		AppMainVo appMainVo = appMainApplication.getEntity(appid);
		List<AppVersionVo> androidList = appVersionApplication.getAppStatus(
				appid, 4);
		for (AppVersionVo versionVo : androidList) {
			if ("android".equals(versionVo.getPlatformid())) {// 上架版本
				int plat_counter = appVersionApplication.findBycount(
						versionVo.getPlatformid(), appid);
				versionVo.setPlat_counter(plat_counter);
				model.addAttribute("androidPub", versionVo);
			} else if ("ios".equals(versionVo.getPlatformid())) {
				int plat_counter = appVersionApplication.findBycount(
						versionVo.getPlatformid(), appid);
				versionVo.setPlat_counter(plat_counter);
				model.addAttribute("iosPub", versionVo);
			}
		}

		String userId = this.getCurrentUserId();
		List<CloudFunctionVo> cloudList = appCloudLinkService
				.getLinkedCloudFunctions(userId, appid);
		model.addAttribute("cloudList", cloudList);
		model.addAttribute("appMainVo", appMainVo);
		String appKey = applicationRegisterApplication.getAppKeyByAppId(appid);
		model.addAttribute("appKey", appKey);
		return "app/app-view";
	}

	/**
	 * 应用编辑页面
	 * 
	 * @param appMainVo
	 * @return
	 */
	@RequestMapping("/update-view")
	public String updateview(Model model, @RequestParam("appId") String appId) {
		AppMainVo appVo = appMainApplication.getEntity(appId);
		List<AppCategoryVo> list = appCategoryApplication.findAll();
		model.addAttribute("list", list);
		model.addAttribute("appVo", appVo);
		return "app/edit-view";
	}

	/**
	 * 更新应用
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/update")
	public Map<String, String> update(AppMainVo appVo) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			AppMainVo updateVo = appMainApplication.getEntity(appVo.getId());
			updateVo.setApp_name(appVo.getApp_name());
			updateVo.setIdentifier(appVo.getIdentifier());
			updateVo.setIcon(appVo.getIcon());
			updateVo.setModified_time(new Date());
			updateVo.setDiscription(appVo.getDiscription());
			updateVo.setCategoryid(appVo.getCategoryid());
			if (StringUtils.isEmpty(updateVo.getSecret())) {
				String secret = UUID.randomUUID().toString();
				updateVo.setSecret(secret);
			}
			appMainApplication.updateEntity(updateVo.getId(), updateVo);
			result.put("id", appVo.getId());
			result.put("result", "success");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("result", "error");
		}
		return result;
	}

	/**
	 * 进入添加云服务页面
	 * 
	 * @param appMainVo
	 * @return
	 */
	@RequestMapping("/cloud/view")
	public String cloud(Model model, @RequestParam("appId") String appId) {
		List<CloudFunctionVo> resultList = new ArrayList<CloudFunctionVo>();
		String userId = this.getCurrentUserId();
		List<CloudFunctionVo> listCloud = cloudFunctionApplication.findAll();// 获取所有云服务
		List<CloudFunctionVo> appCloudList = appCloudLinkService
				.getLinkedCloudFunctions(userId, appId);// 获取已经关联的云服务
		if (appCloudList != null && appCloudList.size() > 0) {
			boolean nolinked = true;
			for (CloudFunctionVo cloud : listCloud) {
				nolinked = true;
				for (CloudFunctionVo appCloud : appCloudList) {
					if (cloud.getId().equals(appCloud.getId())) {
						nolinked = false;
						break;
					}
				}
				if (nolinked) {
					resultList.add(cloud);
				}
			}
		} else {
			resultList.addAll(listCloud);
		}
		model.addAttribute("resultList", resultList);
		return "app/cloud-add";
	}

	/**
	 * 添加云服务
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/cloud/add")
	public Map<String, String> addCloud(@RequestParam("appId") String appId,
			String[] Ids) {
		Map<String, String> result = new HashMap<String, String>();
		String userId = this.getCurrentUserId();
		for (String cloudId : Ids) {
			appCloudLinkApplication.link(appId, cloudId, userId);
		}
		result.put("result", "success");
		return result;
	}

	@ResponseBody
	@RequestMapping("/delete")
	public Map<String, Object> delete(String[] ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (ids != null) {
			for (int i = 0; i < ids.length; i++) {
				appMainApplication.deleteEntity(ids[i]);
			}
		}
		result.put("result", "success");
		return result;
	}

	/**
	 * 获取关联的云服务
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/cloud/{appId}")
	public Map<String, Object> pushCloud(@PathVariable("appId") String appId) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String userId = this.getCurrentUserId();
			List<CloudFunctionVo> cloudList = appCloudLinkService
					.getLinkedCloudFunctions(userId, appId);
			if (cloudList != null && cloudList.size() > 0) {
				result.put("list", cloudList);
			} else {
				result.put("list", new ArrayList<CloudFunctionVo>());
			}
			result.put("result", "success");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("result", "error");
		}
		return result;
	}

	/**
	 * 删除应用
	 * 
	 * @param appId
	 *            应用标识
	 * 
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping("/{appId}/delete")
	public Map<String, Object> deleteAppById(@PathVariable("appId") String appId) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(appId)) {
			String userId = this.getCurrentUserId();
			try {
				// 删除云服务关联
				appCloudLinkService.delLinkedCloudByApps(appId, userId);
				// 删除模块关联
				appVersionWidgetVersionApplication.deleteByApp(appId);
				// 删除版本
				appVersionApplication.deleteByApp(appId);
				// 删除应用
				appMainApplication.deleteEntity(appId);
				result.put("result", "success");
			} catch (Exception e) {
				result.put("result", "error");
				e.printStackTrace();
			}
		}
		return result;
	}
}
